<!--
用法：<qm-file-list :params="{type:'avatar',dataKey:'xxxId'}" ref="picture"></f7-picture-upload>
 -->
<template id="qm-file-list">
    <f7-list class="pic_upload">
        <li class="file-list"  v-if="dbFileList.length>0">
            <div 
              v-for="(file, index) in dbFileList" 
              :key="file.attachmentId" 
              class="file-list-div" 
              @click="openPhotoBrowser(file, index)"
            >
              <!-- 序号 -->
              <div class="file-index" v-if="showIndex == true">
                  <span>{{ index + 1 }}、</span>
              </div>
              <img :src="require(`../../../../assets/img/file/${fileTypeSrc(file)}.png`)" alt="" />
              <span class="file-name">{{ file.fileName }}</span>
            </div>
        </li>
        <v-empty v-else description="暂无数据" />
    </f7-list>
</template>
<script>
import Util from "@/libs/framework/util";
import ImageCompressor from "image-compressor.js";
import FileUpload from "vue-upload-component";
import formatter from "@/libs/framework/formatter";
import Config from "@/libs/config";
import ChunkUploadHandler from "@/libs/polyfill/ChunkUploadHandler";
import Upload from "@/libs/framework/upload";
export default {
    components: {
        FileUpload,
    },
    props: {
        /** 上传附件时，提交给接口的参数：{
         *  dataKey：业务主键,
         *  bizType：业务类型，
         *  type：附件类型，主要用于校验上传文件的合法性；mobile, picture, office
         * }
         */
        params: {
            type: Object,
            default: {},
        },
        dataKey: {
            //对应的工程ID
            type: String,
        },
        extensions: {
            type: String,
        },
        accept: {
            type: String,
        },
        /** 是否允许多选 */
        multiple: {
            type: Boolean,
            default: true,
        },
        /** 允许上传的文件大小 */
        size: {
            type: Number,
            default: 1024 * 1024 * 100,
        },
        chunkUrl: {
            type: String,
            default: Config.api.chunkUploadApi,
        },
        /** 是否显示上传按钮 */
        disabled: {
            type: Boolean,
            default: false,
        },
        // 是否添加时间水印
        timeWatermark: {
            type: Boolean,
            default: false,
        },
        /** 当在for循环里使用此组件时，组件使用者需提供此值，以便区分不同的业务，以防所有项都关联到第一项的组件 */
        uploadId: {
            type: String,
            default: "upload",
        },
        /** 选相册时的参数 */
        galleryOptions: {
            type: Object,
            default: (_) => ({}),
        },
        autoCompress: {
            type: Number,
            default: 300 * 1024,
        },
        /** 是否启用分断上传 */
        chunkEnabled: {
            type: Boolean,
            default: true,
        },
        /** 分片大小 */
        chunkMinSize: {
            type: Number,
            default: 50,
        },
        /** 图片类型 */
        picExtension: {
            type: Array,
            default: () => {
                return ["jpg", "png", "jpeg", "bmp", "webp", "gif"];
            },
        },
        // 上传方式的选择 1相册 2拍照 3文件
        actionsOneGroup: {
            type: Array,
            default: () => [1, 2, 3],
        },
        //是否需要显示序号
        showIndex: {
            type: Boolean,
            default: false,
        },
        imgStyle: {
            type: Object,
            default: () => {
                return { width: 75, height: 75 };
            },
        },
        //是否需要将上传的pdf转为图片，若是启用了这个 注意修改相关的附件列表查询的地方
        pdfToPic: {
            type: Boolean,
            default: false,
        },
        //是否显示二维码编号
        isCode: {
            type: Boolean,
            default: false,
        },
        //二维码数组
        codeList: {
            type: Array,
            default: () => {
                return [];
            },
        },
        defaultFiles: {
            type: Array,
            default: () => {
                return [];
            },
        },
        isDefaultFile:{
            type:Boolean,
            default:false,
        } 
    },
    data () {
        return {
            downUrl: "/api/base/fileupload/downFile",
            getUrl: "/api/base/fileupload/getFiles",
            deleteUrl: "/api/base/fileupload/delFile",
            postUrl: "/api/base/fileupload/uploadFile",
            files: [],
            dbfiles: [],
            dbImgList: [], // 查看时 的图片数据
            dbFileList: [], // 查看时 的pdf等文件类型的数据
            // 1MB by default
            chunkMaxActive: 3,
            chunkMaxRetries: 5,
            popupOpened: false,
            uploadAuto: true,
            handlerClass: ChunkUploadHandler,
            fileThumbPic: [
                "avi",
                "doc",
                "docx",
                "mp4",
                "pdf",
                "ppt",
                "pptx",
                "rar",
                "txt",
                "xls",
                "xlsx",
                "zip",
            ],
            // 1MB by default
            addresses: "", //定位地址：addresses: "广州市黄浦区萝岗福山循环经济产业园"
            latitude: 23.13,
            longitude: 113.27,
            enginee: {}, //工程
            userRoleName: null, //人员类型
            user: {}, //用户信息
            unwacth: null,
        };
    },
    mounted () {
        var self = this;
        if (window.plus) {
            this.postUrl = Config.api.upload;
            this.downUrl = Config.api.download;
            // this.deleteUrl = Config.api.deleteUrl;
        }
    },
    created () {
        var self = this;
        window.enableLog && console.log("created");
        // 如果是设置了不请求文件的方法，则使用自己传入的文件列表
        if(this.isDefaultFile){
            this.mapFileList(this.defaultFiles)
        }else{ // 否则请求文件
            // 监听dataKey是否准备完成
            this.unwacth = this.$watch(
                "params",
                function (val) {
                    if (val.dataKey) {
                        this.fnInit();
                    }
                },
                {
                    deep: true,
                    immediate: true,
                }
            );
        }
    },
    methods: {
        openPhotoBrowser (file, indexs, isUpload) {
            var self = this;
            let photos = [];

            var attachmentId = file.attachmentId
            var fName = file.fileName;
            if (isUpload) {
                fName = file.name;
                attachmentId = file.key
            }

            if (!file.fileType && fName) {
                file.fileType = fName.substring(fName.lastIndexOf("."));
            }

            var extension = file.fileType?.replace(".", "");
            if (extension) {
                extension = extension.toLowerCase();
                file.isPic = this.picExtension.includes(extension);
            }

            if (file.isPic === true) {
                self.dbfiles.forEach((f) => {
                    photos.push(self.downUrl + "?attachmentId=" + f.attachmentId + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken));
                });
                self.files.forEach((f) => {
                    photos.push(self.downUrl + "?attachmentId=" + f.key + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken));
                });
                window.qmSdk.showPhotos({
                    imgs: photos, // 图片地址数组，必填
                    index: indexs, // 从第几个开始浏览，必填
                    success: function () { },
                    fail: function (err) { }
                })
            }
            else {
              if(!fName || fName.lastIndexOf(".")===-1){
                self.$framework.$f7.dialog.alert("非法文件名称");
                return;
              }
                var options = { askRedownload: false };
                // let url = Config.api.downloadPic + `?attachmentId=${attachmentId}` + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken);
                let fileType = fName.substring(fName.lastIndexOf("."));
                let  url = `${Config.api.viewOpenFile}/${attachmentId}${fileType}`;
                window.qmSdk.scanFile({
                    downloadurl: url, // 文件预览网络地址
                    filename: fName,
                    success: function () { },
                    fail: function (err) { }
                })
            }
        },
        fileTypeSrc (item) {
            // 文件类型，用于展示文件类型图片
            let typeList = [
                ".avi",
                ".doc",
                ".docx",
                ".jpeg",
                ".jpg",
                ".pdf",
                ".mp4",
                ".png",
                ".ppt",
                ".pptx",
                ".rar",
                ".txt",
                ".xls",
                ".xlsx",
                ".zip",
            ];
            return typeList.indexOf(item.fileType) != -1
                ? item.fileType.substr(1)
                : "default";
        },
        mapFileList(fileList){
            let self=this
            self.dbFileList = fileList || [];
            if (self.params) {
                self.params.sort = self.dbfiles.length + 1;
            }
        },
        fnInit () {
            let self = this;
            let url = self.getUrl;
            // 取消监听
            if (this.unwacth) this.unwacth();
            self.$f7.request.post(url, self.params, (r) => {
                r = JSON.parse(r);
                if (r?.success) {
                    this.mapFileList(r.parameters.files)
                    return;
                }

                self.$framework.$f7.dialog.toast("获取文件失败");
            });
        },
        removeDbFile (file) {
            var self = this;
            let attachmentId = file.attachmentId;
            if (!attachmentId) {
                self.dbfiles.splice(self.files.indexOf(file), 1);
                return;
            }

            self.$f7.dialog.confirm("该文件已上传成功，确定要删除吗？", (r) => {
                if (!r) {
                    return;
                }
                self.$f7.request.post(
                    self.deleteUrl,
                    { attachmentId: attachmentId, pdfToPic: self.pdfToPic },
                    (r) => {
                        r = JSON.parse(r);
                        if (r && r.success) {
                            let index = self.dbfiles.indexOf(file);
                            self.dbfiles.splice(index, 1);
                            self.$framework.$f7.dialog.toast("文件删除成功");
                            self.$emit("deleteFileAfter", index, file.attachmentId);
                        } else {
                            self.$framework.$f7.dialog.toast(r.message || "文件删除失败");
                        }
                    },
                    (e) => {
                        self.$framework.$f7.dialog.toast("文件删除失败");
                    }
                );

                // file.codeId = "3afd223ca16cf5a791f53d8c8a8b26f1";
                if (!file.codeId) {
                    return;
                }
                //解绑二维码
                self.$f7.request.post(
                    "/quality/concreteWitness/releaseQrCodeWitness",
                    { id: file.codeId },
                    (r) => {
                        r = JSON.parse(r);
                        if (r && r.success) {
                            console.log("二维码解绑成功");
                        } else {
                            console.log(r.message || "二维码解绑失败");
                        }
                    },
                    (e) => {
                        console.log("二维码解绑失败");
                    }
                );
            });
        },
    },
    computed: {
        isPlus () {
            return window.env == "plus";
        },
    },
};
</script>
<style lang="less" scoped>
@deep: ~">>>";
.pic_upload.list{
  padding: 0;
  margin: 0;
  ul{
    margin: 0;
    padding: 0;
  }
  .file-list {
      display: flex;
      flex-direction: column;
      margin-top: 15px;
      background: #F5F8FF;
      padding: 12px;
      border-radius: 2px;
      &-div {
          display: flex;
          align-items: center;
          color: #0f1826;
          padding-bottom: 12px;
          margin-bottom: 12px;
          border-bottom: 1px solid #E9EDF7;

          &:last-child {
              margin-bottom: 0;
              padding-bottom: 0;
              border: none;
          }

          img {
              width: 25px;
              height: auto;
              max-height: 30px;
              margin-right: 10px;
              flex-shrink: 0;
          }

          .file-name {
              flex: 1;
              text-align: left;
              word-break: break-all;
              font-size: 13px;
              color: #61677A;
          }
      }
  }
}
</style>
